package com.yfuxdeer.youchat.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import android.app.Fragment;

import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.activity.ChatActivity;
import com.yfuxdeer.youchat.activity.UserinfoActivity;
import com.yfuxdeer.youchat.adapter.FragmentListAdapter;
import com.yfuxdeer.youchat.pojo.FragmentItem;
import com.yfuxdeer.youchat.pojo.FriendItem;
import com.yfuxdeer.youchat.pojo.Message;
import com.yfuxdeer.youchat.pojo.MessageItem;
import com.yfuxdeer.youchat.service.FriendService;
import com.yfuxdeer.youchat.service.MessageService;
import com.yfuxdeer.youchat.utils.ConvertUtil;
import com.yfuxdeer.youchat.utils.DateUtil;
import com.yfuxdeer.youchat.utils.Store;

import java.util.List;

/**
 * A fragment representing a list of Items.
 */
public class ListFragment extends Fragment {

    private static final String TAG = ListFragment.class.getSimpleName();
    public static final int MESSAGE_ITEM = 0;
    public static final int FRIEND_ITEM = 1;
    private List<FragmentItem> fragmentItemList;
    public static Handler handler;
    private FragmentListAdapter adapter;
    private Store store = Store.getInstance();
    private int type;

    static {
        handler = new Handler();
    }

    private ListView listView;

    public ListFragment() {
    }

    public static ListFragment newInstance() {
        ListFragment fragment = new ListFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        listView = view.findViewById(R.id.list);

        //注册消息界面广播
        if (type == MESSAGE_ITEM) {
            inflater.getContext().registerReceiver(notifyMessageReceiver, new IntentFilter("com.yfuxdeer.youchat.notifyMessageReceiver"));
            inflater.getContext().registerReceiver(iSendMessageReceiver, new IntentFilter("com.yfuxdeer.youchat.iSendMessageReceiver"));
            inflater.getContext().registerReceiver(findMessageItemReceiver, new IntentFilter("com.yfuxdeer.youchat.findMessageItemReceiver"));
        }

        //注册朋友界面广播
        if (type == FRIEND_ITEM) {
            inflater.getContext().registerReceiver(findAllFriendReceiver, new IntentFilter("com.yfuxdeer.youchat.findAllFriendReceiver"));
        }

        //注册都需要的广播
        inflater.getContext().registerReceiver(deleteFriendReceiver, new IntentFilter("com.yfuxdeer.youchat.deleteFriendReceiver"));


        //设置每一项的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String addition = fragmentItemList.get(i).getAddition();
                String title = fragmentItemList.get(i).getTitle();
                if (addition.equals("在线") || addition.equals("离线")) {
                    //跳转到好友界面
                    Intent intent = new Intent(inflater.getContext(), UserinfoActivity.class);
                    intent.putExtra("remark", fragmentItemList.get(i).getTitle());
                    intent.putExtra("user_id", fragmentItemList.get(i).getHead_id());
                    inflater.getContext().startActivity(intent);
                } else {
                    //跳转到聊天界面
                    Intent intent = new Intent(inflater.getContext(), ChatActivity.class);
                    intent.putExtra("nickName", title);
                    intent.putExtra("friend_id", fragmentItemList.get(i).getHead_id());
                    Log.e(TAG, "onItemClick: " + "friend_id = " + fragmentItemList.get(i).getHead_id());
                    inflater.getContext().startActivity(intent);
                }
            }
        });

        //设置每一项的长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.d(TAG, "onItemLongClick: " + "长按了 : " + i);
                String addition = fragmentItemList.get(i).getAddition();
                String friend_id = fragmentItemList.get(i).getHead_id();
                View popup_view = getLayoutInflater().inflate(R.layout.pop_delete, null);
                PopupWindow popupWindow = new PopupWindow(popup_view, ViewGroup.LayoutParams.MATCH_PARENT
                        , view.getHeight());
                popupWindow.setFocusable(true);
                Button delete = popup_view.findViewById(R.id.delete);
                System.out.println(delete);
                if (type == FRIEND_ITEM) {
                    //是好友列表
                    delete.setText("删除好友");
                    delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view_) {
                            View delete_confirm = getLayoutInflater().inflate(R.layout.pop_friend_confirm_delete, null);
                            PopupWindow confirmWindow = new PopupWindow(delete_confirm, ViewGroup.LayoutParams.MATCH_PARENT
                                    , ViewGroup.LayoutParams.MATCH_PARENT);
                            confirmWindow.setFocusable(true);
                            popupWindow.dismiss();
                            Button cancel = delete_confirm.findViewById(R.id.cancel);
                            Button delete_friend = delete_confirm.findViewById(R.id.delete);
                            cancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    confirmWindow.dismiss();
                                }
                            });
                            delete_friend.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //调用服务删除好友
                                    Intent intent = new Intent(inflater.getContext(), FriendService.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("method", FriendService.METHOD.DELETE_FRIEND);
                                    bundle.putString("host_id", store.getCurrentUser().getUsername());
                                    bundle.putString("friend_id", friend_id);
                                    intent.putExtras(bundle);
                                    inflater.getContext().startService(intent);
                                    confirmWindow.dismiss();
                                }
                            });
                            confirmWindow.showAsDropDown(view);
                        }
                    });
                } else {
                    delete.setText("从消息列表中移除");
                    delete.setClickable(true);
                    delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Log.d(TAG, "onClick: " + "点击了移除按钮");
                            deleteMessageItem(friend_id);
                            popupWindow.dismiss(); //隐藏按钮
                        }
                    });
                }
                int location[] = new int[2];
                view.getLocationInWindow(location);
                popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1]);
                return true;
            }
        });

        return view;
    }

    private void deleteMessageItem(String friend_id) {
        if (fragmentItemList == null) {
            return;
        }
        for (FragmentItem fragmentItem : fragmentItemList) {
            if (fragmentItem.getHead_id().equals(friend_id)) {
                fragmentItemList.remove(fragmentItem);
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        init();
    }

    private void init() {
        if (type == MESSAGE_ITEM) {
            //调用服务请求网络查询 加载消息信息
            Intent intent = new Intent(getActivity().getApplicationContext(), MessageService.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("method", MessageService.METHOD.FIND_MESSAGE_ITEM);
            bundle.putString("username", store.getCurrentUser().getUsername());
            intent.putExtras(bundle);
            getActivity().getApplicationContext().startService(intent);
        } else {
            //调用服务请求网络查询 加载好友
            Intent intent = new Intent(getActivity().getApplicationContext(), FriendService.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("method", FriendService.METHOD.FIND_ALL);
            bundle.putString("username", store.getCurrentUser().getUsername());
            intent.putExtras(bundle);
            getActivity().getApplicationContext().startService(intent);
        }
    }


    public void setType(int type) {
        this.type = type;
    }

    private BroadcastReceiver deleteFriendReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            FriendService.RESULT result = (FriendService.RESULT) bundle.getSerializable("result");
            switch (result) {
                case SUCCESS:
                    String friend_id = bundle.getString("friend_id");
                    if (ListFragment.this.fragmentItemList == null) {
                        return;
                    }
                    for (FragmentItem fragmentItem : ListFragment.this.fragmentItemList) {
                        if (fragmentItem.getHead_id().equals(friend_id)) {
                            ListFragment.this.fragmentItemList.remove(fragmentItem);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private BroadcastReceiver notifyMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Message message = (Message) bundle.getSerializable("message");
            boolean isFind = false;
            if (fragmentItemList == null) return;
            //在已有的列表中查找
            for (int i = 0; i < fragmentItemList.size(); i++) {
                if (fragmentItemList.get(i).getHead_id().equals(message.getFrom())) {
                    //找到就修改
                    isFind = true;
                    //删除，在最前面添加
                    FragmentItem item = fragmentItemList.get(i);
                    fragmentItemList.remove(item);
                    item.setSub_title(message.getMsg());
                    fragmentItemList.add(0, item);
                }
            }
            if (!isFind) {
                //没找到就新添加
                FriendItem friendItem = (FriendItem) bundle.getSerializable("friendItem");
                FragmentItem fragmentItem = new FragmentItem(friendItem.getFriend_id(),
                        friendItem.getRemark(), message.getMsg(), DateUtil.getDate(message.getTime()));
                fragmentItemList.add(0, fragmentItem);
            }
            adapter.notifyDataSetChanged();
        }
    };

    private BroadcastReceiver iSendMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Message message = (Message) bundle.getSerializable("message");
            boolean isFind = false;
            if (fragmentItemList == null) return;
            //在已有的列表中查找
            for (int i = 0; i < fragmentItemList.size(); i++) {
                if (fragmentItemList.get(i).getHead_id().equals(message.getTo())) {
                    //找到就修改
                    isFind = true;
                    fragmentItemList.get(i).setSub_title(message.getMsg());
                }
            }
            if (!isFind) {
                //没找到就新添加
                FriendItem friendItem = (FriendItem) bundle.getSerializable("friendItem");
                FragmentItem fragmentItem = new FragmentItem(friendItem.getFriend_id(),
                        friendItem.getRemark(), message.getMsg(), DateUtil.getDate(message.getTime()));
                fragmentItemList.add(fragmentItem);
            }
            adapter.notifyDataSetChanged();
        }
    };

    private BroadcastReceiver findMessageItemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            Bundle bundle = intent.getExtras();
            MessageService.RESULT result = (MessageService.RESULT) bundle.getSerializable("result");
            switch (result) {
                case SUCCESS:
                    List<MessageItem> messageItemList = (List<MessageItem>) bundle.getSerializable("messageItemList");
                    ListFragment.this.fragmentItemList = ConvertUtil.MessageItem2FragmentItem(messageItemList);
                    adapter = new FragmentListAdapter(ListFragment.this.fragmentItemList, getActivity().getApplicationContext());
                    listView.setAdapter(adapter);
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(getActivity().getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private BroadcastReceiver findAllFriendReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            Bundle bundle = intent.getExtras();
            FriendService.RESULT result = (FriendService.RESULT) bundle.getSerializable("result");
            switch (result) {
                case SUCCESS:
                    List<FriendItem> friendItemList = (List<FriendItem>) bundle.getSerializable("friendItemList");
                    ListFragment.this.fragmentItemList = ConvertUtil.FriendItem2FragmentItem(friendItemList);
                    adapter = new FragmentListAdapter(ListFragment.this.fragmentItemList, getActivity().getApplicationContext());
                    listView.setAdapter(adapter);
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(getActivity().getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}